import React, {useEffect, useState, useRef} from "react";
import axios from "axios";
import {Button, Modal, Space, Switch, Table } from "antd";
import {EditOutlined, DeleteOutlined, ExclamationCircleOutlined} from "@ant-design/icons";
import UserForm from "../../../components/user-manage/UserForm";

const { confirm } = Modal;

const roleObj= {
    "1": "superAdmin",
    "2": "admin",
    "3": "editor"
};

// 注意：这个页面只有管理员和超级管理员才有权限访问
export default function UserList() {
    const [dataSource, setDataSource] = useState([]);
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [isUpdateModalVisible, setIsUpdateModalVisible] = useState(false);
    const [roleList, setRoleList] = useState([]);
    const [regionList, setRegionList]= useState([]);
    const addFormRef= useRef(null);
    const updateFormRef= useRef(null);
    const [updateUserId, setUpdateUserId]= useState({});
    const [isDisabledRegion, setIsDisabledRegion]= useState(false);
    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            render: region => {
                return <b>{region==='' ? '全球' : region}</b>
            },
            filters: [
                {
                    text: "全球",
                    value: ""
                },
                ...regionList.map(item=>{
                    return {
                        text: item.title,
                        value: item.value
                    }
                })
            ],
            onFilter: (region, record) => record.region===region
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render: role=>role.roleName
        },
        {
            title: '用户名',
            dataIndex: 'username'
        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render: (roleState, item)=> {
                return <Switch checked={roleState}
                               disabled={item.default}
                               onChange={()=>handleRoleState(item)}
                        />
            }
        },
        {
            title: '操作',
            key: 'operation',
            render: (record) => {
                return (
                    <Space size="middle">
                        <Button danger shape="circle" icon={<DeleteOutlined />} onClick={()=>handleDelete(record)} disabled={record.default}/>
                        <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>handleUpdate(record)} disabled={record.default}/>
                    </Space>
                )
            },
        },
    ];

    const { roleId, region, username } = JSON.parse(localStorage.getItem('token'));
    useEffect(()=>{
        axios.get('/api/users?_expand=role').then(response=>{
            // console.log(response.data);
            const data= response.data;

            setDataSource(roleObj[roleId]==="superAdmin" ? data : [
                ...data.filter(item=>{
                    if(item.username===username || (item.region===region && roleObj[item.roleId]==="editor")) {
                        return true;
                    }
                    return false;
                })
            ]);
        });
    }, [roleId, region, username]);

    useEffect(()=>{
        axios.get('/api/roles').then(response=>{
            // console.log(response.data);
            setRoleList(response.data);
        });
    }, []);

    useEffect(()=>{
        axios.get('/api/regions').then(response=>{
            // console.log(response.data);
            setRegionList(response.data);
        });
    }, []);

    // 添加用户
    const handleAddFormOk= ()=>{
        // console.log('add', addFormRef);
        addFormRef.current.validateFields().then(values=>{
            setIsAddModalVisible(false);

            // 先将数据post到后端保存起来，再设置dataSource(为了获取id)
            axios.post('/api/users', {
                // "username": values.username,
                // "password": values.password,
                // "region": values.region,
                // "roleId": values.roleId,
                ...values,
                "roleState": true,
                "default": false
            }).then(response=>{
                setDataSource([...dataSource, {
                    ...response.data,
                    role: roleList.filter(item=>item.id===values.roleId)[0]
                }]);
                addFormRef.current.resetFields();
            });
        })
    }
    const handleAddFormCancel= ()=>{
        setIsAddModalVisible(false);
        addFormRef.current.resetFields();
    }

    // 更新用户的状态：是否允许登录
    const handleRoleState= (item)=>{
        // console.log(item);
        item.roleState= !item.roleState;
        setDataSource([...dataSource]);
        axios.patch(`/api/users/${item.id}`, {
            roleState: item.roleState
        });
    }

    // 删除用户
    const handleDelete= (record)=>{
        confirm({
            title: '是否想要删除此项?',
            icon: <ExclamationCircleOutlined />,
            content: '删除操作不可撤回，请谨慎操作!!!',
            onOk() {
                // console.log(record);
                setDataSource(dataSource.filter(data=>{
                    return data.id !== record.id;
                }));
                axios.delete(`/api/users/${record.id}`).then(()=>{
                    console.log('后端删除成功')
                });
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    // 用户信息更新
    // const handleUpdate= (record)=>{
    //     setIsUpdateModalVisible(true);  // 异步更新状态
    //     // 设置100毫秒的延迟 确保from组件已经加载完毕, 避免对话框模块还没显示，也就是表单还没挂载就调用了setFieldsValue 而造成的报错
    //     setTimeout(()=>{
    //         updateFormRef.current.setFieldsValue(record);
    //     }, 100);
    //     setUpdateUser(record);
    // }
    const handleUpdate= async (record)=>{
        await setIsUpdateModalVisible(true);
        if(record.roleId === 1) {  // 超级管理员角色
            setIsDisabledRegion(true); // 禁用表单中的区域选项
        } else {
            setIsDisabledRegion(false);
        }
        setUpdateUserId(record.id);
        updateFormRef.current.setFieldsValue(record);
    }
    const handleUpdateFormOk= ()=>{
        updateFormRef.current.validateFields().then(values=>{
            setIsUpdateModalVisible(false);
            setIsDisabledRegion(!isDisabledRegion);
            setDataSource(dataSource.map((item)=>{
                if(item.id===updateUserId) {
                    return {
                        ...item,
                        ...values,
                        role: roleList.filter(data=>data.id===values.roleId)[0]
                    }
                }
                return item;
            }));

            axios.patch('/api/users/'+updateUserId, {
                "username": values.username,
                "password": values.password,
                "region": values.region,
                "roleId": values.roleId
            }).then(response=>{
                updateFormRef.current.resetFields();
            });
        })
    }
    const handleUpdateFormCancel= ()=>{
        setIsUpdateModalVisible(false);
        updateFormRef.current.resetFields();
        setIsDisabledRegion(!isDisabledRegion);
    }

    return (
        <div>
            <Button type="primary" onClick={ ()=>setIsAddModalVisible(true)}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} pagination={{ pageSize: 5 }} rowKey={ item=>item.id }/>

            <Modal title="添加用户" visible={isAddModalVisible} okText="添加" cancelText="取消"
                   onOk={handleAddFormOk} onCancel={handleAddFormCancel}>
                <UserForm roleList={roleList} regionList={regionList} ref={ addFormRef } />
            </Modal>

            <Modal title="更新用户" visible={isUpdateModalVisible} okText="更新" cancelText="取消"
                   onOk={handleUpdateFormOk} onCancel={handleUpdateFormCancel}>
                <UserForm roleList={roleList}
                          regionList={regionList}
                          isDisabledRegion={isDisabledRegion}
                          ref={ updateFormRef }
                          isUpdate={ true }
                />
            </Modal>
        </div>
    );
};
